<template>
  <div>
    <div class="row">
      <div class="col"></div>
      <el-form :inline="true">
        <el-form-item label="团队">
          <el-select v-model="teamid" multiple collapse-tags filterable>
            <el-option v-for="item in getteam" :key="item.ID" :label="item.name" :value="Number(item.ID)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="团员">
          <el-select v-model="userids" collapse-tags multiple filterable>
            <el-option v-for="item in getusers" :key="Number(item.ID)" :label="String(item.name)"
              :value="Number(item.ID)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="答题时间">
          <el-date-picker v-model="times" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间"
            :shortcuts="shortcuts">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="题目ID">
          <el-input v-model.number="questionid" placeholder="请输入题单ID"></el-input>
        </el-form-item>
        <el-form-item label="题单ID">
          <el-input v-model.number="questionbankid" placeholder="请输入题单ID"></el-input>
        </el-form-item>
        <el-form-item label="题单模式">
          <el-select v-model="questionbanktype">
            <el-option label="全部" :value="0"></el-option>
            <el-option label="练习模式" :value="1"></el-option>
            <el-option label="测评模式" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="附加信息">
          <el-select v-model="attr" multiple collapse-tags filterable>
            <el-option label="团队名称" value="团队名称"></el-option>
            <el-option label="手机号" value="手机号"></el-option>
            <el-option label="学校" value="学校"></el-option>
            <el-option label="姓名" value="姓名"></el-option>
          </el-select>
        </el-form-item>
        <br />
        <el-row>
          <el-col :span="12">
            <el-form-item label="总条数：">{{ count1 }} </el-form-item>
            <el-form-item label="用户数">{{ userids.length }} </el-form-item>
          </el-col>
          <el-col :span="12" class="text-right">
            <el-button @click="start" type="primary">查询</el-button>
            <el-button @click="() => download()" type="primary">下载</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="row mb-1">
      <div class="col">
        <el-table :data="userquestion" border height="65vh" style="width: 100%">
          <el-table-column prop="user.name" label="用户" width="120">
          </el-table-column>
          <el-table-column prop="questionid" label="题目ID" width="100">
          </el-table-column>
          <el-table-column prop="questionbankid" label="题单ID" width="100">
          </el-table-column>
          <el-table-column prop="type" label="题目类型" width="120">
          </el-table-column>
          <el-table-column prop="createdAt" label="答题时间" :formatter="({ createdAt }) => TimeYH(createdAt)" width="150">
          </el-table-column>
          <el-table-column prop="question.name" label="题目"> </el-table-column>
          <el-table-column prop="resultdata" label="AC" width="100">
          </el-table-column>
          <el-table-column prop="resultdataarr" label="测试点" width="350">
          </el-table-column>
          <el-table-column prop="teamname" v-if="attr.includes('团队名称')" label="团队名称" width="350">
          </el-table-column>
          <el-table-column prop="user.xingming" v-if="attr.includes('姓名')" label="姓名" width="150">
          </el-table-column>
          <el-table-column prop="user.phonenum" v-if="attr.includes('手机号')" label="手机号" width="150">
          </el-table-column>
          <el-table-column prop="resultdataarr" v-if="attr.includes('学校')" label="学校" width="150">
            <template #default="scope">
              {{ scope.row.user.info?.school }}
            </template>
          </el-table-column>
          <el-table-column prop="result" label="其他信息" width="100">
            <template #default="scope">

              <el-button text v-show="scope.row.type == '代码'" @click="download(scope.row)">
                下载源码</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="row  mb-1">
      <div class="col">
        <el-pagination :page-size="limit" :total="count1" @size-change="handleSizeChange" @current-change="change"
          layout="sizes, prev, pager, next" :current-page="Math.floor(offset / limit) + 1"></el-pagination>
      </div>
    </div>

  </div>
</template>

<script lang="ts" setup>
import {
  Iobj,
  asyncadminselectuserquestion,
  asyncselectteamuser,
} from "../../../api";
import { ElMessage } from "element-plus";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import {
  computed,
  inject,
  onMounted,
  onUnmounted,
  ref,
  watch,
} from "vue";
import { onBeforeRouteUpdate, useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { TimeYH } from "../../../util/time";
import { once } from "underscore";

import { Storekey } from "../../../interface";
import { getExceltodownload } from "../../../util/excel";
import moment from "moment";


const attr = ref<string[]>([])


const handleSizeChange = (val: number) => {
  router.push({
    query: {
      ...roue.value,
      limit: val,
      questionid: questionid.value,
      questionbankid: questionbankid.value
    }
  })
}
const userquestion = ref<Studycodemodel.Iuserquestion[]>([]);
const route = useRoute();
const router = useRouter();
const roue = computed(() => {
  return route.query;
});
const count1 = ref(0);
const order = computed(() => {
  return roue.value.order || "ID";
});
const store = useStore(Storekey);
const getteam = computed<Studycodemodel.Iteam[]>(() => {
  return store.getters.getteam;
});
const getusers = ref<Array<Studycodemodel.Iuser>>([]);
const headnavdialogVisible = inject("headnavdialogVisible", () => { });
const user = computed<Studycodemodel.Iuser | undefined>(() => {
  return store.getters.getuser;
});
const times = ref<[number, number]>([Date.now() - 1000 * 60 * 60 * 24 * 7, Date.now()]);
const height = ref(window.innerHeight - 74);
function onresize(e: UIEvent) {
  height.value = window.innerHeight - 74;
}
window.onresize = onresize;

const offset = computed(() => {
  return Number(roue.value.offset) || 0;
});
const isad = computed(() => {
  return Number(roue.value.isad) || 0;
});
const limit = computed(() => {
  return Number(roue.value.limit) || 20;
});
const questionid = ref<number>();
const teamid = ref<number[]>([]);
const userids = ref<Array<number | undefined>>([]);
const questionbanktype = ref<number>(0);
onUnmounted(() => {
  window.onresize = () => { };
});

onBeforeRouteUpdate(() => {
  questionid.value = Number(roue.value.questionid) || undefined;
  questionbankid.value =
    (roue.value.questionbankid as unknown as number) || undefined;
  start();
});

const questionbankid = ref<number>();

async function start() {
  const userid = userids.value;
  const Iobj: Iobj<Studycodemodel.Iuserquestion> = {
    _limit: limit.value,
    _offset: offset.value,
    _order: 'ID',
    _sortable: 'DESC'
  };
  if (userid.length) {
    Iobj.userid = userid;
  }
  if (times.value) {
    Iobj.createdAt = {
      lt: times.value[1],
      gt: times.value[0],
    };
  }
  if (questionbanktype.value === 1) {
    Iobj.testid = {
      is: null,
    };
  }
  if (questionbanktype.value === 2) {
    Iobj.testid = {
      not: null,
    };
  }

  if (questionbankid.value) {
    Iobj.questionbankid = questionbankid.value;
  }
  if (questionid.value) {
    Object.assign(Iobj, {
      questionid: questionid.value,
    });
  }
  const { rows, count } = await asyncadminselectuserquestion(
    Object.assign(Iobj)
  );
  count1.value = count;
  userquestion.value = rows
}

onMounted(() => {
  try {
    store.dispatch("actionteam");
  } catch (e: any) {
    ElMessage.error(e);
  }
  questionid.value = Number(roue.value.questionid) || undefined
  teamid.value = roue.value.teamid ? [Number(roue.value.teamid)] : []
  questionbankid.value = Number(roue.value.questionbankid as unknown as number) || undefined
});

function change(r: number) {
  router.push({
    name: "答题记录",
    query: {
      limit: limit.value,
      order: order.value,
      offset: (r - 1) * limit.value,
      questionid: questionid.value,
      questionbankid: questionbankid.value,
    },
  });
}

const onc = once(start);

watch(
  () => teamid.value,
  (n) => {
    if (n) {
      const team = getteam.value.find((e) => teamid.value.includes(e.ID));
      asyncselectteamuser({
        teamid: n,
        _limit: 999999
      }).then((e) => {
        const { rows } = e;
        getusers.value = rows.map((v) => {
          const { user, username } = v;
          if (username && user) {
            user.name = username;
          }
          return user as Studycodemodel.Iuser;
        });
        if (team && team.user) {
          getusers.value.push(team.user);
        }
        userids.value = getusers.value.map((v) => v?.ID);
        onc();
      });
    } else {
      getusers.value = [];
      userids.value = [];
    }
  }
);



function download(data?: Studycodemodel.Iuserquestion) {
  const data1: string[][] = [
    ["用户", "题目ID", "题单ID", "答题时间", "题目名称", '答案', "答案/代码", '是否评测', '团队名称', '手机号', '姓名', '学校'],
  ];
  if (data) {
    data1.push(
      [String(data.user?.name),
      String(data.questionid),
      String(data.questionbankid),
      TimeYH(data.createdAt),
      String(data.question?.name),
      String(data.resultdata),
      String(data.context),
      String(data.testid ? '是' : '否'),
      String(data.teamname),
      String(data.user?.phonenum),
      String(data.user?.xingming),
      String(data.user?.info?.school),
      ]
    )
  } else {
    userquestion.value.forEach((e) => {
      let {
        user,
        question,
        questionbankid,
        questionid,
        createdAt,
        resultdata,
        context
      } = e;
      data1.push([
        String(user?.name),
        String(questionid),
        String(questionbankid),
        TimeYH(createdAt),
        String(question?.name),
        String(resultdata),
        String(context),
        String(e.testid ? '是' : '否'),
        String(e.teamname),
        String(e.user?.phonenum),
        String(e.user?.xingming),
        String(e.user?.info?.school),
      ]);
    });
  }

  if (data1.length > 1) {
    const n: Record<string, number> = {
      团队名称: 8,
      手机号: 9,
      姓名: 10,
      学校: 11,
    }
    attr.value.forEach(c => {
      console.log(c)
      delete n[c]
    })
    const n1 = Object.values(n)
    const t = data1.map(c => {
      const data: string[] = []
      c.forEach((e, k) => {
        if (!n1.includes(k)) {
          data.push(e)
        }
      })
      return data
    })
    getExceltodownload(t, "学生答题信息");
  }
}



const shortcuts = [
  {
    text: "上周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "本周",
    value: () => {
      const end = new Date();

      const start = moment().day(1).unix() * 1000;
      return [start, end];
    },
  },
  {
    text: "本月",
    value: () => {
      const end = new Date();
      const start = moment().date(1).unix() * 1000;
      return [start, end];
    },
  },
  {
    text: "最近90天",
    value: () => {
      const end = new Date();
      const start = moment().date(-90).unix() * 1000;
      return [start, end];
    },
  },
]


</script>

<style scoped>
.gre {
  background-color: var(--color-cheng);
  color: #fff;
}

.gre:hover {
  background-color: var(--color-cheng);
  color: #fff;
}

.gre:active {
  background-color: var(--color-cheng);
  color: #fff;
}

.gre:focus {
  background-color: var(--color-cheng);
  color: #fff;
}

.Accepted {
  color: #53c419;
}

.Unaccepted {
  color: #9d3dcf;
}

.CompileError {
  color: #e74b3c;
}

/* .Unshown {

} */
</style>

